package zorm

import (
	"errors"
	"strconv"
)

type SUser struct {
	Id       int      `zorm:"column:id;primary_key"`
	Uname    string   `zorm:"column:uname;size:30;not null"`
	Upass    string   `zorm:"column:upass;size:30;not null"`
	Umail    string   `zorm:"column:umail;size:30;not null"`
	Image    int      `zorm:"column:image;not null"`
	Parent   int      `zorm:"column:parent;not null"`
	LoginUrl string   `zorm:"column:loginurl;size:255;not null"`
	Groups   []SGroup `zorm:"column:groups"` //用户组
	IsUse    bool     `zorm:"column:isuse;not null"`
}

func (t *SUser) TableName() string {
	return "s_user"
}

// 返回可以操作的安全字段列表
func (t *SUser) GetSafeFields(uid int) []string {
	if uid != 0 {
		return []string{"Uname", "Upass", "Image", "LoginuUrl"}
	}
	return []string{}
}
func (t *SUser) Scan(uid int) error {
	//不管是谁,必写的字段
	if len(t.Uname) == 0 {
		return errors.New("名称必须填写")
	}
	if len(t.Umail) == 0 {
		return errors.New("名称必须填写")
	}
	if uid != 0 {
		if t.Parent > 0 {
			if ok := HashUid(uid, t.Parent); ok == false {
				return errors.New("无权限")
			}
		} else {
			t.Parent = uid //设置新用户的UID
		}
	}
	return nil
}

// Login 用户登录
func Login(uname string, upass string) (*SUser, error) {
	if (len(uname) == 0) || (len(upass) == 0) {
		return nil, errors.New("用户名或密码不能为空!")
	}
	db := GetDB("")
	user := &SUser{}
	if err := db.First(nil, user, "[Umail,=,'"+uname+"']", nil); err != nil {
		return nil, errors.New("用户名不存在!")
	}
	if user.Upass != upass {
		return nil, errors.New("密码不正确!")
	}
	if user.IsUse == false {
		return nil, errors.New("用户已停用!")
	}
	return user, nil
}

// suser.GetChilds 返回指定用户的子用户
func GetChilds(uid int) ([]int, error) {
	suser := new(SUser)
	db := GetDB("")
	sql := "SELECT id FROM " + suser.TableName() + " WHERE id in (SELECT id FROM " + suser.TableName() + " WHERE parent=" + strconv.Itoa(uid) + ")"
	rows, err := db.Db.Query(sql)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var ret []int
	ret = append(ret, uid)
	for rows.Next() {
		var id int
		if err := rows.Scan(&id); err != nil {
			var lid int64
			if err := rows.Scan(&lid); err != nil {
				panic("无法识别的id类型" + err.Error())
			}
			id = int(lid)
		}
		ret = append(ret, id)
	}
	return ret, nil
}

//判断指定用户是否属于当前用户
func HashUid(uid int, id int) bool {
	if uid == 0 {
		return true
	}
	if uid < 0 {
		return false
	}
	if uid == id {
		return true
	}
	ids, err := GetChilds(uid)
	if err != nil {
		return false
	}
	for _, v := range ids {
		if id == v {
			return true
		}
	}
	return false
}
